package cn.cs.controller;

import cn.cs.client.AgentUserClient;
import cn.cs.client.AgentUserForUserDB;
import cn.cs.client.ShopOrderClient;
import cn.cs.common.*;
import cn.cs.config.AgentConfig;
import cn.cs.config.AlipayConfig;
import cn.cs.config.WXPayConfig;
import cn.cs.pojo.ShopOrder;
import cn.cs.util.WXPayConstants;
import cn.cs.util.WXPayRequest;
import cn.cs.util.WXPayUtil;
import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

@Controller
@RequestMapping("/repAppPay")
public class RepAppPayController {

    @Resource
    private WXPayConfig wxPayConfig;
    @Resource
    private AlipayConfig alipayConfig;
    @Resource
    private RedisUtils redisUtils;
    @Resource
    private ShopOrderClient shopOrderClient;
    @Resource
    private AgentUserClient agentUserClient;
    @Resource
    private AgentConfig agentConfig;
    @Resource
    private AgentUserForUserDB agentUserForUserDB;

    /****
     * 维修工APP商城订单付款接口（支付宝支付）
     * @param
     * @param
     * @return
     */
    @RequestMapping("/orderPay")
    @ResponseBody
    public Dto orderPay(HttpServletRequest request, HttpServletResponse response) throws Exception{
            String orderId = request.getParameter("orderId");
                    ShopOrder order= shopOrderClient.getShopOrderById(Long.valueOf(orderId));
            if(EmptyUtils.isEmpty(order)){
                return   DtoUtil.returnFail("未找到订单", "002");
            }
            response.setHeader("Access-Control-Allow-Origin", "*");
//        String product_code = "FAST_INSTANT_TRADE_PAY";
//        String WIDout_trade_no = order.getOrderNumber();
//        String WIDsubject ="购买商品";
//        String WIDtotal_amount = order.getCountMoney();
            // SDK 公共请求类，包含公共请求参数，以及封装了签名与验签，开发者无需关注签名与验签
            // 调用RSA签名方式
            AlipayClient client = new DefaultAlipayClient(alipayConfig.getUrl(),
                    alipayConfig.getAppID(), alipayConfig.getRsaPrivateKey(),
                    alipayConfig.getFormat(), alipayConfig.getCharset(),
                    alipayConfig.getAlipayPublicKey(), alipayConfig.getSignType());
            // 封装请求支付信息

            AlipayTradeAppPayRequest alipay_request = new AlipayTradeAppPayRequest();

            AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
//        model.setBody("sasdasd");
            model.setSubject("购买商品");
            model.setOutTradeNo( order.getOrderNumber());
            model.setTimeoutExpress("30m");
            model.setTotalAmount(order.getCountMoney());
//            model.setTotalAmount("0.1");
            model.setProductCode(order.getOrderNumber());
            alipay_request.setBizModel(model);
//            alipay_request.setReturnUrl("localhost:8088/api/shopPayReturn");
            alipay_request.setNotifyUrl("https://www.zzzsyh.com/cs_pay/aliPayNotify");
            try {
                // 调用SDK生成表单
                AlipayTradeAppPayResponse res = client.sdkExecute(alipay_request);
                return DtoUtil.returnDataSuccess(res.getBody());
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return   DtoUtil.returnFail("支付失败", "002");
            }

    }

    /****
     * 支付宝付款成功后异步回调接口
     * @param request
     * @param
     * @return
     */
    @RequestMapping("/aliPayNotify")
    @ResponseBody
    public void aliPayNotify(HttpServletRequest request,  HttpServletResponse response) throws Exception{
        //获取支付宝POST过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
//切记alipaypublickey是支付宝的公钥，请去open.alipay.com对应应用下查看。
//boolean AlipaySignature.rsaCheckV1(Map<String, String> params, String publicKey, String charset, String sign_type)
        boolean flag = AlipaySignature.rsaCheckV1(params, alipayConfig.getAlipayPublicKey(), alipayConfig.getCharset(),alipayConfig.getSignType());
        if(flag){
            String state= params.get("trade_status");
            if("TRADE_SUCCESS".equals(state)) {
                String shopOrdernum = params.get("out_trade_no");
                int count = shopOrderClient.getStateProByOutNum(shopOrdernum);
                if(count <1){
                    Map<String, Object> param = new HashMap<String, Object>();
                    param.put("order_number", shopOrdernum);
                    param.put("update_time", DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
                    param.put("pay_time", DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
                    param.put("state", "1");
                    shopOrderClient.updateShopOrderState(param);
                }
            }
        }
    }


    /****
     * 维修工APP商城订单付款接口（微信支付）
     * @param
     * @param
     * @return
     */
    @RequestMapping(value = "/wxRepOrderPay")
    @ResponseBody
    public Dto wxRepOrderPay(HttpServletResponse response, HttpServletRequest request) throws Exception{
        String token = request.getHeader("token");
            HashMap<String, String> data = new HashMap<String, String>();
            WXPayRequest wxPayRequest = new WXPayRequest(this.wxPayConfig);
            try {
                String orderId = request.getParameter("orderId");
//                Map<String,Object> order
                        ShopOrder order= shopOrderClient.getShopOrderById(Long.valueOf(orderId));

                data.put("body", "购买商品");
                data.put("out_trade_no", order.getOrderNumber());
                String count_money = String.valueOf(Double.valueOf(order.getCountMoney())*100);
                count_money = count_money.substring(0,count_money.lastIndexOf("."));
                data.put("total_fee",count_money );//付款金额
//                data.put("total_fee", "1");//付款金额
//                data.put("notify_url","http://www.zzzsyh.com/cs_pay/wxPayNotify");
                Map<String, String> r = wxPayRequest.unifiedorderApp(data);
                String resultCode = r.get("result_code");
                if (resultCode.equals("SUCCESS")) {
                    Map<String,Object> resultMap =new HashMap<String, Object>();
                    resultMap.put("timestamp", String.valueOf(System.currentTimeMillis() / 1000));
                    resultMap.put("package", "Sign=WXPay");
                    resultMap.put("appid", r.get("appid"));
                    resultMap.put("partnerid", r.get("mch_id"));
                    resultMap.put("prepayid", r.get("prepay_id"));
                    resultMap.put("noncestr", r.get("nonce_str"));
                    resultMap.put("sign", r.get("sign"));
                    String newSing =  getSign(resultMap,wxPayConfig.getKey());
                    resultMap.put("sign", newSing);
                    return DtoUtil.returnDataSuccess(resultMap);
                } else {
                    return DtoUtil.returnFail("订单支付异常", Constants.WxpayStatus.DDZFYC);
                }
            } catch (Exception e) {
                e.printStackTrace();
                return DtoUtil.returnFail("订单运行异常", Constants.WxpayStatus.DDYXYC);
            }
    }
    /****
     * 微信付款成功后异步回调接口
     * @param request
     * @param
     * @return
     */
    @RequestMapping(value = "/wxPayNotify")
    @ResponseBody
    public String wxPayNotify(HttpServletRequest request, HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        WXPayRequest wxPayRequest = new WXPayRequest(this.wxPayConfig);
        Map<String, String> result = new HashMap<String, String>();
        Map<String, String> params = null;
        String returnxml = "";
        try {
            InputStream inputStream;
            StringBuffer sb = new StringBuffer();
            //以字节流的形式读取request中的数据
            inputStream = request.getInputStream();
            String s;
            BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
            while ((s = in.readLine()) != null) {
                sb.append(s);
            }
            in.close();
            inputStream.close();
            params = WXPayUtil.xmlToMap(sb.toString());
            String returnCode = params.get("return_code");
            if (returnCode.equals("SUCCESS")) {
                //判断签名是否正确
                boolean flag = wxPayRequest.isResponseSignatureValid(params);
                if (flag) {
                    //获取微信订单号
                    String transactionId = params.get("transaction_id");
                    //获取商户订单号
                    String shopOrdernum = params.get("out_trade_no");
                    if(EmptyUtils.isNotEmpty(shopOrdernum)){
                        Map<String,Object> param = new HashMap<String, Object>();
                        param.put("order_number",shopOrdernum);
                        param.put("update_time", DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
                        param.put("pay_time",DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
                        param.put("state","1");
                        shopOrderClient.updateShopOrderState(param);
                        result.put("return_code", "SUCCESS");
                        result.put("return_msg", "OK");
                    }

                } else {
                    result.put("return_code", "FAIL");
                    result.put("return_msg", "签名失败");
                }
            } else {
                result.put("return_code", "FAIL");
                result.put("return_msg", "支付失败");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            returnxml = WXPayUtil.mapToXml(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return returnxml;
    }


    public String getSign(Map<String, Object> data,String key) throws Exception {
        Set<String> keySet = data.keySet();
        String[] keyArray = keySet.toArray(new String[keySet.size()]);
        Arrays.sort(keyArray);
        StringBuilder sb = new StringBuilder();
        for (String k : keyArray) {
            if (k.equals(WXPayConstants.FIELD_SIGN)) {
                continue;
            }
            if (data.get(k).toString().trim().length() > 0) // 参数值为空，则不参与签名
                sb.append(k).append("=").append(data.get(k).toString().trim()).append("&");
        }
        sb.append("key=").append(key);
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        byte[] array = new byte[0];
        try {
            array = md.digest(sb.toString().getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        StringBuilder sb2 = new StringBuilder();
        for (byte item : array) {
            sb2.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
        }
        return sb2.toString().toUpperCase();
    }


//    /****
//     * 经销商支付宝app登录接口
//     * @param
//     * @param
//     * @return
//     */
//    @RequestMapping("/agentAlipayToLogin")
//    @ResponseBody
//    public Dto agentAlipayToLogin(HttpServletRequest request, HttpServletResponse response) throws Exception{
//        String token = request.getHeader("token");
//        Map<String,Object> tokenMap = tokenUtils.checkToken(request.getHeader("agent"),token,request.getHeader("code"));
//        if("0".equals(tokenMap.get("errorCode"))){
//            return  DtoUtil.returnFail(tokenMap.get("errorMsg").toString(),"003");
//        }else{
//            if("1".equals(tokenMap.get("errorCode"))){
//                return  DtoUtil.returnFail("token已过期请置换token","004");
//            }
//        }
//        Map<String,Object> user = JSON.parseObject(redisUtils.get(token), Map.class);
//        if(EmptyUtils.isEmpty(user)){
//            return DtoUtil.returnFail("用户未登录","001");
//        }else {
//            Map<String,String> param = new HashMap<String, String>();
//            param.put("apiname","com.alipay.account.auth");
//            param.put("method","alipay.open.auth.sdk.code.get");
//            param.put("app_id",alipayConfig.getJxsAppID());
//            param.put("app_name","mc");
//            param.put("biz_type","openservice");
//            param.put("pid",alipayConfig.getJxsPid());
//            param.put("product_id","APP_FAST_LOGIN");
//            param.put("scope","kuaijie");
//            param.put("auth_type","AUTHACCOUNT");
//            param.put("sign_type","RSA2");
//           String sign =  AlipaySignature.rsaSign(param,alipayConfig.getJxsRsaPrivateKey(),alipayConfig.getCharset());
//            param.put("sign",sign);
//            try {
//                // 调用SDK生成表单
//                return DtoUtil.returnDataSuccess(param);
//            } catch (Exception e) {
//                // TODO Auto-generated catch block
//                e.printStackTrace();
//                return   DtoUtil.returnFail("支付失败", "002");
//            }
//        }
//    }
//
//    /****
//     * 维修工支付宝app登录接口
//     * @param
//     * @param
//     * @return
//     */
//    @RequestMapping("/repairAlipayToLogin")
//    @ResponseBody
//    public Dto repairAlipayToLogin(HttpServletRequest request, HttpServletResponse response) throws Exception{
//        String token = request.getHeader("token");
//        Map<String,Object> tokenMap = tokenUtils.checkToken(request.getHeader("agent"),token,request.getHeader("code"));
//        if("0".equals(tokenMap.get("errorCode"))){
//            return  DtoUtil.returnFail(tokenMap.get("errorMsg").toString(),"003");
//        }else{
//            if("1".equals(tokenMap.get("errorCode"))){
//                return  DtoUtil.returnFail("token已过期请置换token","004");
//            }
//        }
//        RepairUser user = JSON.parseObject(redisUtils.get(token), RepairUser.class);
//        if(EmptyUtils.isEmpty(user)){
//            return DtoUtil.returnFail("用户未登录","001");
//        }else {
//            Map<String,String> param = new HashMap<String, String>();
//            param.put("apiname","com.alipay.account.auth");
//            param.put("method","alipay.open.auth.sdk.code.get");
//            param.put("app_id",alipayConfig.getAppID());
//            param.put("app_name","mc");
//            param.put("biz_type","openservice");
//            param.put("pid",alipayConfig.getJxsPid());
//            param.put("product_id","APP_FAST_LOGIN");
//            param.put("scope","kuaijie");
//            param.put("auth_type","AUTHACCOUNT");
//            param.put("sign_type","RSA2");
//            String sign =  AlipaySignature.rsaSign(param,alipayConfig.getRsaPrivateKey(),alipayConfig.getCharset());
//            param.put("sign",sign);
//            try {
//                // 调用SDK生成表单
//                return DtoUtil.returnDataSuccess(param);
//            } catch (Exception e) {
//                // TODO Auto-generated catch block
//                e.printStackTrace();
//                return   DtoUtil.returnFail("支付失败", "002");
//            }
//        }
//    }



    /****
     * 经销商B级付款开通权限
     * @param
     * @param
     * @return
     */
    @RequestMapping("/hasPower")
    @ResponseBody
    public Dto hasPower(HttpServletRequest request, HttpServletResponse response) throws Exception{
        String token = request.getHeader("token");
        Map<String,Object> agentUser =  JSON.parseObject(redisUtils.getString(token), Map.class);
            String type = request.getParameter("type");
            response.setHeader("Access-Control-Allow-Origin", "*");
            String id =agentUser.get("id").toString();
            String money = "";
        List<Map<String,Object>> list =agentUserClient.getAgentAreasByAgentUserId(id);
        Map<String,Object> map = list.get(0);
            Map<String,Object> area  = agentUserForUserDB.getAgentAreaLevel(map.get("agent_area").toString());
            String area_level = area.get("area_type").toString();
            if("A".equals(area_level)){
                money = agentConfig.getProvince();
            }
            if("B".equals(area_level)){
                money = agentConfig.getCity();
            }
            if("C".equals(area_level)){
                money = agentConfig.getArea();
            }
            if(EmptyUtils.isEmpty(money)){
                return DtoUtil.returnFail("没有找到经销商管辖区域","002");
            }
            String invoice = request.getParameter("invoice");
            String seqNum = String.valueOf((int)((Math.random()*9+1)*1000));
            if("1".equals(invoice)){
                String invoiceType= request.getParameter("invoiceType");
                String title= request.getParameter("title");
                String phone= request.getParameter("phone");
                String email= request.getParameter("email");
                Map<String,Object> invoiceMap = new HashMap<String, Object>();
                invoiceMap.put("id",IdWorker.getId());
                invoiceMap.put("type",invoiceType);
                invoiceMap.put("title",title);
                invoiceMap.put("phone",phone);
                invoiceMap.put("email",email);
                invoiceMap.put("agent_id",id);
                invoiceMap.put("order_num",id+seqNum);
                agentUserForUserDB.insertAgentInvoice(invoiceMap);
            }
            id = id + seqNum;
            if("1".equals(type)){
                AlipayClient client = new DefaultAlipayClient(alipayConfig.getUrl(),
                        alipayConfig.getAppID(), alipayConfig.getRsaPrivateKey(),
                        alipayConfig.getFormat(), alipayConfig.getCharset(),
                        alipayConfig.getAlipayPublicKey(), alipayConfig.getSignType());
                // 封装请求支付信息
                AlipayTradeAppPayRequest alipay_request = new AlipayTradeAppPayRequest();
                AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
                model.setSubject("开通权限");
                model.setOutTradeNo(id);
                model.setTimeoutExpress("30m");
                model.setTotalAmount(money);
                model.setProductCode(id);
                alipay_request.setBizModel(model);
                alipay_request.setNotifyUrl("https://www.zzzsyh.com/cs_pay/hasPowerAliPayNotify");
                try {
                    // 调用SDK生成表单
                    AlipayTradeAppPayResponse  res = client.sdkExecute(alipay_request);
                    return DtoUtil.returnDataSuccess(res.getBody());
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    return   DtoUtil.returnFail("支付失败", "002");
                }
            }else{
                HashMap<String, String> data = new HashMap<String, String>();
                WXPayRequest wxPayRequest = new WXPayRequest(this.wxPayConfig);
                try {
                    data.put("body", "开通权限");
                    data.put("out_trade_no", id);
                    data.put("total_fee", String.valueOf(Integer.valueOf(money)*100));//付款金额
                    Map<String, String> r = wxPayRequest.unifiedorderJXSApp(data);
                    System.out.println(r.toString());
                    String resultCode = r.get("result_code");
                    if (resultCode.equals("SUCCESS")) {
                        Map<String,Object> resultMap =new HashMap<String, Object>();
                        resultMap.put("timestamp", String.valueOf(System.currentTimeMillis() / 1000));
                        resultMap.put("package", "Sign=WXPay");
                        resultMap.put("appid", r.get("appid"));
                        resultMap.put("partnerid", r.get("mch_id"));
                        resultMap.put("prepayid", r.get("prepay_id"));
                        resultMap.put("noncestr", r.get("nonce_str"));
                        resultMap.put("sign", r.get("sign"));
                        String newSing =  getSign(resultMap,wxPayConfig.getKey());
                        resultMap.put("sign", newSing);
                        return DtoUtil.returnDataSuccess(resultMap);
                    } else {
                        return DtoUtil.returnFail("订单支付异常", Constants.WxpayStatus.DDZFYC);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    return DtoUtil.returnFail("订单运行异常", Constants.WxpayStatus.DDYXYC);
                }
            }

    }

    /****
     * B级经销商开通权限支付宝付款成功后异步回调接口
     * @param request
     * @param
     * @return
     */
    @RequestMapping("/hasPowerAliPayNotify")
    @ResponseBody
    public void hasPowerAliPayNotify(HttpServletRequest request,  HttpServletResponse response) throws Exception{
        //获取支付宝POST过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }
        boolean flag = AlipaySignature.rsaCheckV1(params, alipayConfig.getAlipayPublicKey(), alipayConfig.getCharset(),alipayConfig.getSignType());
        if(flag){
            String state= params.get("trade_status");
            if("TRADE_SUCCESS".equals(state)){
                String outNum = params.get("out_trade_no");
                String agent_id = outNum.substring(0,outNum.length()-4);
                Map<String,Object> param = new HashMap<String, Object>();
                String time = DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss");
                Map<String,Object> areaMap = agentUserForUserDB.getAgentAreaLevel(agent_id);
                String area = areaMap.get("area_type").toString();
                param.put("id",IdWorker.getId());
                if("A".equals(area)){
                    param.put("pay_money",agentConfig.getProvince());
                }
                if("B".equals(area)){
                    param.put("pay_money",agentConfig.getCity());
                }
                if("C".equals(area)){
                    param.put("pay_money",agentConfig.getArea());
                }
                param.put("order_num",outNum);
                param.put("agent_id",agent_id);
                param.put("update_time",time);
                param.put("create_time",time);
                param.put("pay_time",time);
                param.put("pay_style","支付宝");
                param.put("agent_area",area);

                Calendar curr = Calendar.getInstance();
                curr.set(Calendar.YEAR,curr.get(Calendar.YEAR)+1);
                curr.set(Calendar.DAY_OF_YEAR,curr.get(Calendar.DAY_OF_YEAR)-1);
                Date date=curr.getTime();
                param.put("end_time", DateUtil.format(date,"yyyy-MM-dd HH:mm:ss"));
                int count = agentUserClient.getAgentPayByOutNum(outNum);
                if(count < 1){
                    int n = agentUserClient.insertAgentPay(param);
                    if(n>0){
                        Map<String,Object> agentUser = new HashMap<String, Object>();
                        agentUser.put("id",agent_id);
                        agentUser.put("is_power","1");
                        agentUser.put("power_time",time);
                        agentUserClient.updateAgent(agentUser);
                    }
                }
            }
        }
    }


    /****
     * 微信付款成功后异步回调接口
     * @param request
     * @param
     * @return
     */
    @RequestMapping(value = "/hasPowerWXNotify")
    @ResponseBody
    public String hasPowerWXNotify(HttpServletRequest request, HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        WXPayRequest wxPayRequest = new WXPayRequest(this.wxPayConfig);
        Map<String, String> result = new HashMap<String, String>();
        Map<String, String> params = null;
        String returnxml = "";
        try {
            InputStream inputStream;
            StringBuffer sb = new StringBuffer();
            //以字节流的形式读取request中的数据
            inputStream = request.getInputStream();
            String s;
            BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
            while ((s = in.readLine()) != null) {
                sb.append(s);
            }
            in.close();
            inputStream.close();
            params = WXPayUtil.xmlToMap(sb.toString());
            String returnCode = params.get("return_code");
            if (returnCode.equals("SUCCESS")) {
                //判断签名是否正确
                boolean flag = wxPayRequest.isResponseSignatureValid(params);
                if (flag) {
                    String outNum = params.get("out_trade_no");
                    if(EmptyUtils.isNotEmpty(outNum)){
                        String agent_id = outNum.substring(0,outNum.length()-4);
                        Map<String,Object> param = new HashMap<String, Object>();
                        String time = DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss");
                        List<Map<String,Object>> list = agentUserClient.getAgentAreasByAgentUserId(agent_id);
                        Map<String,Object> map = list.get(0);
                        Map<String,Object> areaMap = agentUserForUserDB.getAgentAreaLevel(map.get("agent_area").toString());
                        String area = areaMap.get("area_type").toString();
                        param.put("id",IdWorker.getId());
                        if("A".equals(area)){
                            param.put("pay_money",agentConfig.getProvince());
                        }
                        if("B".equals(area)){
                            param.put("pay_money",agentConfig.getCity());
                        }
                        if("C".equals(area)){
                            param.put("pay_money",agentConfig.getArea());
                        }
                        param.put("order_num",outNum);
                        param.put("agent_id",agent_id);
                        param.put("update_time",time);
                        param.put("create_time",time);
                        param.put("pay_time",time);
                        param.put("pay_style","微信");
                        param.put("agent_area",area);
                        Calendar curr = Calendar.getInstance();
                        curr.set(Calendar.YEAR,curr.get(Calendar.YEAR)+1);
                        curr.set(Calendar.DAY_OF_YEAR,curr.get(Calendar.DAY_OF_YEAR)-1);
                        Date date=curr.getTime();
                        param.put("end_time", DateUtil.format(date,"yyyy-MM-dd HH:mm:ss"));
                        int count = agentUserClient.getAgentPayByOutNum(outNum);
                        if(count < 1){
                            int n = agentUserClient.insertAgentPay(param);
                            if(n>0){
                                Map<String,Object> agentUser = new HashMap<String, Object>();
                                agentUser.put("id",agent_id);
                                agentUser.put("is_power","1");
                                agentUser.put("power_time",time);
                                agentUserClient.updateAgent(agentUser);
                            }
                        }

                        result.put("return_code", "SUCCESS");
                        result.put("return_msg", "OK");
                    }
                } else {
                    result.put("return_code", "FAIL");
                    result.put("return_msg", "签名失败");
                }
            } else {
                result.put("return_code", "FAIL");
                result.put("return_msg", "支付失败");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            returnxml = WXPayUtil.mapToXml(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return returnxml;
    }
}
